// src/pages/AdminTools.js - 管理员工具页面

import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Typography, Card, List, Button, Space, Tag, Input,
  Table, Modal, message, Popconfirm, Tooltip, Badge,
  Select, DatePicker, Row, Col, Statistic
} from 'antd';
import {
  ToolOutlined, DeleteOutlined, EyeOutlined, UserOutlined,
  PushpinOutlined, LockOutlined, UnlockOutlined, SearchOutlined,
  ExclamationCircleOutlined, CheckCircleOutlined, CloseCircleOutlined
} from '@ant-design/icons';
import { topics } from '../services';

const { Title, Text } = Typography;
const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

const AdminTools = () => {
  const navigate = useNavigate();
  const [posts, setPosts] = useState([]);
  const [comments, setComments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('posts');
  const [searchKeyword, setSearchKeyword] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [messageApi, contextHolder] = message.useMessage();
  const [currentUser, setCurrentUser] = useState(null);
  const [stats, setStats] = useState({
    totalPosts: 0,
    totalComments: 0,
    pinnedPosts: 0,
    reportedPosts: 0
  });

  useEffect(() => {
    loadCurrentUser();
    loadPosts();
    loadStats();
  }, []);

  const loadCurrentUser = () => {
    const user = JSON.parse(localStorage.getItem('starrypt_user') || 'null');
    setCurrentUser(user);

    // 检查是否是管理员
    if (!user || (user.role !== 'admin' && user.role !== 'moderator')) {
      message.error('您没有权限访问此页面');
      navigate('/home');
    }
  };

  const loadPosts = async () => {
    try {
      setLoading(true);
      // 获取所有话题的帖子
      const topicsResponse = await topics.getTopics();

      if (topicsResponse.success) {
        const allPosts = [];
        const topicsList = topicsResponse.data.topics || [];

        // 遍历每个话题获取帖子
        for (const topic of topicsList) {
          try {
            const postsResponse = await topics.getTopicPosts(topic.id, { page: 1, limit: 50 });
            if (postsResponse.success) {
              const topicPosts = postsResponse.data.posts || [];
              allPosts.push(...topicPosts);
            }
          } catch (error) {
            console.warn(`获取话题 ${topic.id} 的帖子失败:`, error);
          }
        }

        setPosts(allPosts);
      }
    } catch (error) {
      console.error('加载帖子失败:', error);
      messageApi.error('加载帖子失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const loadStats = async () => {
    try {
      // 这里可以调用专门的统计API，现在用模拟数据
      setStats({
        totalPosts: posts.length,
        totalComments: 0,
        pinnedPosts: posts.filter(p => p.isPinned).length,
        reportedPosts: 0
      });
    } catch (error) {
      console.error('加载统计数据失败:', error);
    }
  };

  const handleDeletePost = async (postId) => {
    try {
      const response = await topics.deleteTopicPost(postId);
      if (response.success) {
        messageApi.success('帖子删除成功');
        loadPosts();
        loadStats();
      } else {
        messageApi.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除帖子失败:', error);
      messageApi.error('删除帖子失败: ' + error.message);
    }
  };

  const handlePinPost = async (postId, isPinned) => {
    try {
      // 置顶功能暂时不可用，显示提示
      messageApi.info('置顶功能正在开发中，敬请期待');
    } catch (error) {
      console.error('置顶操作失败:', error);
      messageApi.error('置顶操作失败: ' + error.message);
    }
  };

  const handleViewPost = (postId) => {
    navigate(`/topics/${postId}`);
  };

  const formatTime = (timeString) => {
    if (!timeString) return '未知';
    const time = new Date(timeString);
    return time.toLocaleString();
  };

  // 帖子表格列定义
  const postColumns = [
    {
      title: 'ID',
      dataIndex: 'postId',
      key: 'postId',
      width: 80,
      render: (id, record) => record.postId || record.id
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
      render: (title, record) => (
        <div>
          <Text strong>{title}</Text>
          {record.isPinned && <Tag color="red" style={{ marginLeft: 8 }}>置顶</Tag>}
          {record.category && <Tag color="blue" style={{ marginLeft: 4 }}>{record.category}</Tag>}
        </div>
      )
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      width: 120
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      render: formatTime
    },
    {
      title: '统计',
      key: 'stats',
      width: 120,
      render: (_, record) => (
        <Space direction="vertical" size="small">
          <Text type="secondary">浏览: {record.viewCount || 0}</Text>
          <Text type="secondary">点赞: {record.likes || 0}</Text>
          <Text type="secondary">评论: {record.comments || 0}</Text>
        </Space>
      )
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看">
            <Button
              type="text"
              icon={<EyeOutlined />}
              size="small"
              onClick={() => handleViewPost(record.postId || record.id)}
            />
          </Tooltip>
          <Tooltip title={record.isPinned ? "取消置顶" : "置顶"}>
            <Button
              type="text"
              icon={<PushpinOutlined />}
              size="small"
              style={{ color: record.isPinned ? '#ff4d4f' : undefined }}
              onClick={() => handlePinPost(record.postId || record.id, record.isPinned)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个帖子吗？"
            description="删除后无法恢复"
            icon={<ExclamationCircleOutlined style={{ color: 'red' }} />}
            onConfirm={() => handleDeletePost(record.postId || record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
                size="small"
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  const filteredPosts = posts.filter(post => {
    const matchesSearch = !searchKeyword ||
      post.title?.toLowerCase().includes(searchKeyword.toLowerCase()) ||
      post.author?.toLowerCase().includes(searchKeyword.toLowerCase());

    const matchesFilter = filterStatus === 'all' ||
      (filterStatus === 'pinned' && post.isPinned) ||
      (filterStatus === 'normal' && !post.isPinned);

    return matchesSearch && matchesFilter;
  });

  if (!currentUser || (currentUser.role !== 'admin' && currentUser.role !== 'moderator')) {
    return null;
  }

  return (
    <div style={{ background: '#f0f2f5', minHeight: 'calc(100vh - 200px)' }}>
      {contextHolder}
      <div style={{ maxWidth: 1400, margin: '0 auto', padding: '24px' }}>

        {/* 页面标题 */}
        <div style={{ marginBottom: 24 }}>
          <Title level={2} style={{ margin: 0 }}>
            <ToolOutlined /> 管理员工具
          </Title>
          <Text type="secondary" style={{ fontSize: '16px' }}>
            话题社区内容管理
          </Text>
        </div>

        {/* 统计概览 */}
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="总帖子数"
                value={stats.totalPosts}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="总评论数"
                value={stats.totalComments}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="置顶帖子"
                value={stats.pinnedPosts}
                prefix={<PushpinOutlined />}
                valueStyle={{ color: '#fa8c16' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="举报待处理"
                value={stats.reportedPosts}
                prefix={<ExclamationCircleOutlined />}
                valueStyle={{ color: '#ff4d4f' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 帖子管理 */}
        <Card
          title="帖子管理"
          extra={
            <Space>
              <Search
                placeholder="搜索帖子标题或作者"
                allowClear
                style={{ width: 250 }}
                onSearch={setSearchKeyword}
              />
              <Select
                value={filterStatus}
                onChange={setFilterStatus}
                style={{ width: 120 }}
              >
                <Option value="all">全部</Option>
                <Option value="pinned">置顶</Option>
                <Option value="normal">普通</Option>
              </Select>
              <Button onClick={loadPosts}>刷新</Button>
            </Space>
          }
        >
          <Table
            columns={postColumns}
            dataSource={filteredPosts}
            rowKey={(record) => record.postId || record.id}
            loading={loading}
            pagination={{
              pageSize: 20,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
            }}
            scroll={{ x: 1000 }}
          />
        </Card>
      </div>
    </div>
  );
};

export default AdminTools;